package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jmatio.io.MatFileReader;
import com.jmatio.types.MLArray;
import com.jmatio.types.MLDouble;
import com.mathworks.engine.EngineException;
import com.mathworks.engine.MatlabEngine;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.TAdsbHistoryData;
import com.ruoyi.common.core.domain.entity.TAdsbOutput;
import com.ruoyi.common.core.domain.entity.TJszHistoryData;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IAdsbOutputService;
import com.ruoyi.system.service.IAdsbHistoryDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.Timestamp;

/**
 * @Auther: Stanley.Y
 * @Date: 2024/6/18 15:05
 * @Description: ADS-B模式下功能请求Controller类
 * @Version 1.0.0
 */

@RestController
@Anonymous
@RequestMapping("/system/adsb")
public class AdsbModeController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(AdsbModeController.class);

    @Autowired
    private IAdsbOutputService adsbOutputService;

    @Autowired
    private IAdsbHistoryDataService adsbHistoryDataService;

    @Value("${output.adsb_fun0}")
    private String adsbFunOutputPath;

    @Value("${algorithm.adsb}")
    private String adsbAlgorithmPath;

    @Value("${adsb_data.filepath1}")
    private String adsbDataFilepath1;

    @Value("${adsb_data.filepath2}")
    private String adsbDataFilepath2;

    @Value("${adsb_data.locationreal}")
    private String adsbDataLocationReal;

    @Value("${adsb_data.interferenc_degree_q}")
    private String adsbDataInterferencDegreeQ;

    // 定义MatlabEngine变量
    private static MatlabEngine engine;

    static {
        try {
            engine = MatlabEngine.startMatlab();
            log.debug("***************** ADS-B Matlab engine初始化开始 *****************：");
        } catch (EngineException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static MatlabEngine getInstance() throws EngineException, InterruptedException {
        log.debug("Engine status =====: " + engine);
        if(engine == null){
            log.debug("getInstance创建*****************：");
            engine = MatlabEngine.startMatlab();
        }
        return engine;
    }

    /**
     * 获取干扰源强度数据文件结果集
     * @return
     */
    @GetMapping("/getAdsbOutputList")
    public AjaxResult getAdsbOutputList() {
        List<TAdsbOutput> adsbOutputList = adsbOutputService.getAdsbOutputList();
        return success(adsbOutputList);
    }

    @GetMapping("/getAdsbOutputList2")
    public AjaxResult getAdsbOutputList2() {
        File[] files = this.getFilsListByTimeDes(adsbFunOutputPath);
        JSONObject jsonObject = new JSONObject();
        if (files != null) {
            try {
                JSONArray locationArray = new JSONArray();
                for (int i = 0; i < files.length; i++) {
                    String name = files[i].getName();
                    Path path = Paths.get(files[i].getAbsolutePath());
                    FileTime lastModifiedTime = Files.getLastModifiedTime(path);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String lastModifiedTimeStr = sdf.format(lastModifiedTime.toMillis());

                    JSONObject fileObject = new JSONObject();
                    fileObject.put("name", name);
                    fileObject.put("time", lastModifiedTimeStr);
                    locationArray.add(fileObject);
                }
                jsonObject.put("Files", locationArray);
            } catch (Exception ex) {
                log.error(ex.getMessage());
            }
        }
        log.debug("读取fun_0输出文件对象 ===： " + jsonObject.toString());
        return success(jsonObject.toString());
    }

    /**
     * 根据干扰强度结果集中一条记录ID，查询该条干扰强度记录数据。
     * @param id
     * @return
     */
    @GetMapping("/getAdsbIntensityDataById")
    public AjaxResult getAdsbIntensityDataById(String id){
        TAdsbOutput adsbOutput = adsbOutputService.getAdsbOutputById(id);
        JSONObject jsonObject = new JSONObject();
        if(adsbOutput != null){
            String matFilePath = adsbFunOutputPath + adsbOutput.getOutputFile();
            double[][] intensityDatas = this.readQMatFile(matFilePath);
            jsonObject.put("name", adsbOutput.getName());
            jsonObject.put("minLon", adsbOutput.getLon1());
            jsonObject.put("maxLon", adsbOutput.getLon2());
            jsonObject.put("minLat", adsbOutput.getLat1());
            jsonObject.put("maxLat", adsbOutput.getLat2());
            jsonObject.put("gridSize", "[" + adsbOutput.getGrid() + "," + adsbOutput.getGrid() + "]");
            StringBuffer dataBuf = new StringBuffer();
            dataBuf.append("[");
            for (int i = intensityDatas.length - 1; i >= 0; i--) {
                for (int j = 0; j < intensityDatas[i].length; j++) {
                    dataBuf.append("[" + i + "," + j + "," + intensityDatas[i][j] + "],");
                }
            }
            dataBuf.append("]");
            String result = dataBuf.toString().substring(0,dataBuf.toString().length()-2) + "]";
            jsonObject.put("data", result);
        }
        return success(jsonObject.toString());
    }

    /**
     * 调用异步执行fun_0算法：干扰源强度算法
     *
     * @param scenename
     * @param lon1
     * @param lat1
     * @param lon2
     * @param lat2
     * @param grid
     * @return
     */
    @GetMapping("/callFun0")
    public void callFun0(String scenename, String lon1, String lat1, String lon2, String lat2, String grid) {
        /**
        MatlabEngine engine = null;
        try {
            engine = MatlabEngine.startMatlab();
            engine.eval("cd " + adsbAlgorithmPath);
            engine.fevalAsync("fun_0", lat1, lat2, lon1, lon2, grid, adsbDataFilepath1, adsbDataFilepath2, adsbFunOutputPath);
            engine.close(); // 关闭Matlab引擎
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (engine == null) {
                try {
                    // 断开 Matlab 引擎连接
                    engine.disconnect();
                    log.debug("Matlab引擎已断开连接!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
         */
        double gridDouble = Double.parseDouble(grid);
        TAdsbOutput adsbOutput = new TAdsbOutput();
        adsbOutput.setName(scenename);
        adsbOutput.setLon1(Double.parseDouble(lon1));
        adsbOutput.setLat1(Double.parseDouble(lat1));
        adsbOutput.setLon2(Double.parseDouble(lon2));
        adsbOutput.setLat2(Double.parseDouble(lat2));
        adsbOutput.setGrid(gridDouble);
        // 入库t_adsb_output表记录
        if (gridDouble == 0.8) {
            adsbOutput.setOutputFile("Q8.mat");
        }
        if (gridDouble == 0.2) {
            adsbOutput.setOutputFile("Q20.mat");
        }
        adsbOutputService.insertAdsbOutputRecord(adsbOutput);
    }

    /**
     * 同步异步执行fun_2算法: 干扰源定位算法
     *
     * @param lon1
     * @param lat1
     * @param lon2
     * @param lat2
     * @param gridLength
     * @return
     */
    @GetMapping("/callFun2")
    public AjaxResult callFun2(String lon1, String lat1, String lon2, String lat2, String gridLength) {
        JSONObject jsonObject = new JSONObject();
        // 创建干扰定位对象
        JSONArray locationArray = new JSONArray();
        double[][] randomLocations = this.getRandomLocation(Double.parseDouble(lon1), Double.parseDouble(lon2), Double.parseDouble(lat1), Double.parseDouble(lat2));
        for (int n = 0; n < randomLocations.length; n++) {
            JSONObject location = new JSONObject();
            location.put("x", randomLocations[n][0]);
            location.put("y", randomLocations[n][1]);
            locationArray.add(location);
        }
        jsonObject.put("Locations", locationArray);
        return success(jsonObject.toString());
    }

    /**
     * 删除ADS-B历史的干扰源强度*.mat数据
     */
    @Log(title = "干扰源强度数据维护", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id) {
        return toAjax(adsbOutputService.deleteAdsbOutputRecord(id));
    }

    /**
     * 读取目录下所有文件，并根据文件最后修改时间倒排序返回文件集合。
     *
     * @param filePath
     * @return File[]
     */
    private File[] getFilsListByTimeDes(String filePath) {
        File[] files = null;
        try {
            File file = new File(filePath);
            files = file.listFiles();

            if (files != null) {
                Arrays.sort(files, new Comparator<File>() {
                    public int compare(File f1, File f2) {
                        long diff = f1.lastModified() - f2.lastModified();
                        if (diff > 0)
                            return -1;
                        else if (diff == 0)
                            return 0;
                        else
                            return 1;
                    }

                    public boolean equals(Object obj) {
                        return true;
                    }
                });
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return files;
    }

    /**
     * 在输入的经纬度范围，随机生成5组经纬度值
     * @param minLongitude
     * @param maxLongitude
     * @param minLatitude
     * @param maxLatitude
     * @return
     */
    private double[][] getRandomLocation(double minLongitude, double maxLongitude, double minLatitude, double maxLatitude) {
        // 设置要生成的坐标数量
        int numCoordinates = 5;
        // 创建随机数生成器
        Random random = new Random();
        // 生成随机经纬度值
        double[][] result = new double[numCoordinates][2];
        for (int i = 0; i < numCoordinates; i++) {
            double latitude = minLatitude + (maxLatitude - minLatitude) * random.nextDouble();
            double longitude = minLongitude + (maxLongitude - minLongitude) * random.nextDouble();
            result[i][0] = longitude;
            result[i][1] = latitude;
            log.debug("Random Coordinate " + (i + 1) + ": (" + latitude + ", " + longitude + ")");
        }
        return result;
    }

    /**
     * 读取解析*.mat文件数据
     * @param filePath MAT文件路径
     * @return 构造出数据字符串
     */
    private double[][] readQMatFile(String filePath){
        double[][] data = null;
        try {
            // 读取MAT文件
            MatFileReader matReader = new MatFileReader(filePath);

            // 获取MAT文件中的所有变量
            Map<String, MLArray> content = matReader.getContent();
            // log.debug("Content =====: " + content);

            // 遍历每个变量
            for (Map.Entry<String, MLArray> entry : content.entrySet()) {
                String varName = entry.getKey();
                MLArray mlArray = entry.getValue();

                // 假设我们知道MAT文件中保存的是double类型的数据
                if (mlArray instanceof MLDouble) {
                    MLDouble mlDouble = (MLDouble) mlArray;
                    data = mlDouble.getArray(); // 获取double数组

                    // 打印数据
//                    log.debug("Variable Name: " + varName);
//                    log.debug("Data: ");
//                    for (int i = 0; i < data.length; i++) {
//                        for (int j = 0; j < data[i].length; j++) {
//                            System.out.print(data[i][j] + " ");
//                        }
//                        System.out.println();
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    // ****************************** V4模型算法 ******************************** //
    /**
     * 干扰源生成模式（自动生成）
     * @param interferenceNum 生成干扰源数量
     * @param range 干扰源干扰半径
     * @param areaNum 区域编号
     * @param startTime 时间起点
     * @param endTime 时间终点
     */
    @GetMapping("/dataProcess1")
    public AjaxResult dataProcess1(String interferenceNum, String range, String areaNum, String startTime, String endTime) {
        log.debug("***** ADS-B dataProcess1() 开始执行 *****");
        JSONObject jsonObject = null;
        try {
            String adsFilePath1Data = adsbDataFilepath1 + "AREA" + areaNum + "_DATA1.mat";
            String adsFilePath1Hex = adsbDataFilepath1 + "AREA" + areaNum + "_HEX1.mat";
            String adsFilePath2Data = adsbDataFilepath2 + "AREA" + areaNum + "_DATA2.mat";
            String adsFilePath2Hex = adsbDataFilepath2 + "AREA" + areaNum + "_HEX2.mat";
            String filepathLocationReal = adsbDataLocationReal + "AREA" + areaNum + "_LocationReal.mat";
            engine = this.getInstance();
            engine.eval("cd " + adsbAlgorithmPath);
            Object[] res = engine.feval(3, "data_process1", adsFilePath1Data, adsFilePath1Hex, adsFilePath2Data, adsFilePath2Hex, filepathLocationReal,
                    Integer.parseInt(interferenceNum), Integer.parseInt(range), Integer.parseInt(areaNum), Double.parseDouble(startTime), Double.parseDouble(endTime));
            log.debug("location_real result ===: " + res[2]); // location_real

            // ************ 结果解析 ************ //
            // 解析算法调用结果
            double[][] locationRealArray = (double[][]) res[2];
            JSONArray locationRealJsonArray = new JSONArray();
            for (int i = 0; i < locationRealArray.length; i++) {
                log.debug("LocationReal [" + i + "] X =: " + locationRealArray[i][0] + "; Y =: " + locationRealArray[i][1]);
                JSONObject location = new JSONObject();
                location.put("longitude", locationRealArray[i][0]);
                location.put("latitude", locationRealArray[i][1]);
                locationRealJsonArray.add(location);
            }
            jsonObject = new JSONObject();
            jsonObject.put("location_real", locationRealJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return error("干扰定位接口处理异常");
        }
        return success(jsonObject.toString());
    }

    /**
     * 干扰源生成模式（手动选择）
     * @param areaNum 区域编号
     * @param startTime 时间起点
     * @param endTime 时间终点
     * @param interferenceNum 生成干扰源数目
     * @param locationReal 干扰源真实位置，数据格式：x1,y1;x2,y2;.....;xn,yn
     * @param range 干扰源影响半径
     */
    @GetMapping("/dataProcess2")
    public AjaxResult dataProcess2(String areaNum, String startTime, String endTime, String interferenceNum, String locationReal,
                             String range) {
        log.debug("***** ADS-B dataProcess2() 开始执行 *****");
        JSONObject jsonObject = null;
        try {
            String[] locationReals = locationReal.split(";");
            int locRealCount = locationReals.length;
            double[][] locationRealDoubles = new double[locRealCount][2];
            for (int i = 0; i < locRealCount; i++) {
                locationRealDoubles[i][0] = Double.parseDouble(locationReals[i].split(",")[0]);
                locationRealDoubles[i][1] = Double.parseDouble(locationReals[i].split(",")[1]);
            }
            // 设置数据目录文件
            String adsFilePath1Data = adsbDataFilepath1 + "AREA" + areaNum + "_DATA1.mat";
            String adsFilePath1Hex = adsbDataFilepath1 + "AREA" + areaNum + "_HEX1.mat";
            String adsFilePath2Data = adsbDataFilepath2 + "AREA" + areaNum + "_DATA2.mat";
            String adsFilePath2Hex = adsbDataFilepath2 + "AREA" + areaNum + "_HEX2.mat";
            String filepathLocationReal = adsbDataLocationReal + "AREA" + areaNum + "_LocationReal.mat";
            engine = this.getInstance();
            engine.eval("cd " + adsbAlgorithmPath);
            Object[] res = engine.feval(3, "data_process2", adsFilePath1Data, adsFilePath1Hex, adsFilePath2Data, adsFilePath2Hex, filepathLocationReal,
                    Double.parseDouble(areaNum), Double.parseDouble(startTime), Double.parseDouble(endTime), Integer.parseInt(interferenceNum), locationRealDoubles, Integer.parseInt(range));
            log.debug("location_real result ===: " + res[2]); // location_real

            // ************ 结果解析 ************ //
            // 解析算法调用结果
            double[][] locationRealArray = (double[][]) res[2];
            JSONArray locationRealJsonArray = new JSONArray();
            for (int i = 0; i < locationRealArray.length; i++) {
                log.debug("LocationReal [" + i + "] X =: " + locationRealArray[i][0] + "; Y =: " + locationRealArray[i][1]);
                JSONObject location = new JSONObject();
                location.put("longitude", locationRealArray[i][0]);
                location.put("latitude", locationRealArray[i][1]);
                locationRealJsonArray.add(location);
            }
            jsonObject = new JSONObject();
            jsonObject.put("location_real", locationRealJsonArray);
            log.debug("返回的数据对象 ===： " + jsonObject.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return error("干扰定位接口处理异常");
        }
        return success(jsonObject.toString());
    }

    /**
     * 计算并保存adsb分析过程及成果数据。
     * @return
     */
    @PostMapping("/startCalculLocatAndDetect")
    public AjaxResult startCalculLocatAndDetect(@RequestBody TAdsbHistoryData tAdsbHistoryData) {
        JSONObject result = new JSONObject();
        try {
            // step1:先获取tAdsbHistoryData的name，paramsData，再加上createTime，status将这几个参数入库
            log.debug("step1: name:" + tAdsbHistoryData.getName());
            log.debug("step1: paramsData:" + tAdsbHistoryData.getParamsData());
            tAdsbHistoryData.setCreateTime(new Timestamp(System.currentTimeMillis()));
            log.debug("step1: CreateTime:" + tAdsbHistoryData.getCreateTime());

            tAdsbHistoryData.setStatus("正在计算");
            log.debug("step1: status:" + tAdsbHistoryData.getStatus());
            // 先存没有结果的数据
            adsbHistoryDataService.saveInitParams(tAdsbHistoryData);
            int id = tAdsbHistoryData.getId();

            // 调用干扰程度检测函数：fun_1.m
            String adsFilePath2Data = adsbDataFilepath2 + "AREA" + tAdsbHistoryData.getAreaNum() + "_DATA2.mat";
            String adsFilePath2Hex = adsbDataFilepath2 + "AREA" + tAdsbHistoryData.getAreaNum() + "_HEX2.mat";
            String QPath = adsbDataInterferencDegreeQ + "AREA" + tAdsbHistoryData.getAreaNum() + "_Q.mat";
            String filepathLocationReal = adsbDataLocationReal + "AREA" + tAdsbHistoryData.getAreaNum() + "_LocationReal.mat";
            log.debug("adsFilePath2Hex:"+adsFilePath2Hex);
            log.debug("filepathLocationReal:"+filepathLocationReal);
            engine = this.getInstance();
            engine.eval("cd " + adsbAlgorithmPath);
            Object[] res1 = engine.feval(1, "fun_1", adsFilePath2Data, adsFilePath2Hex, QPath, tAdsbHistoryData.getAreaNum(), tAdsbHistoryData.getGridStep());
            log.debug("res1.length:" + res1.length);

            // 解析干扰程度结果Q
            JSONArray qJsonObj = new JSONArray();
            double[][] QArray = (double[][]) res1;
            for (int i = QArray.length - 1; i >= 0; i--) {
                for(int j = 0; j < QArray[i].length; j++){
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(i);
                    jsonArray.add(j);
                    jsonArray.add(QArray[i][j]);
                    qJsonObj.add(jsonArray);
                }
            }
            result.put("interferenceMatrixData", qJsonObj);
            log.debug("==========================================:");

            log.debug("adsFilePath2Data:"+adsFilePath2Data);
            log.debug("adsFilePath2Hex:"+adsFilePath2Hex);
            log.debug("filepathLocationReal:"+filepathLocationReal);
            // 调用干扰源定位接口：fun_2.m
            Object[] res2 = engine.feval(6, "fun_2", adsFilePath2Data, adsFilePath2Hex, filepathLocationReal, tAdsbHistoryData.getAreaNum());
            log.debug("get location_detect result ===: " + res2[0]);
            log.debug("get location_real result ===: " + res2[1]);
            log.debug("get LocationError_avg result ===: " + res2[2]);
            log.debug("get T result ===: " + res2[3]);
            log.debug("get point1 result ===: " + res2[4]);
            log.debug("get point2 result ===: " + res2[5]);

            // 解析location_detect数据
            JSONArray locationDetectJsonArray = new JSONArray();
            if(res2[0] != null)
            {
                double[][] locationDetectArray = (double[][]) res2[0];
                for (int i = 0; i < locationDetectArray.length; i++) {
                    log.debug("LocationDetect [" + i + "] X =: " + locationDetectArray[i][0] + "; Y =: " + locationDetectArray[i][1] + "; T =: " + locationDetectArray[i][2]);
                    JSONObject location = new JSONObject();
                    location.put("longitude", locationDetectArray[i][0]);
                    location.put("latitude", locationDetectArray[i][1]);
                    location.put("type", locationDetectArray[i][2]);
                    locationDetectJsonArray.add(location);
                }
            }
            result.put("location_detect", locationDetectJsonArray);

            // 解析location_real数据;
            JSONArray locationRealJsonArray = new JSONArray();
            if(res2[1] != null)
            {
                double[][] locationRealArray = (double[][]) res2[1];
                for (int i = 0; i < locationRealArray.length; i++)
                {
                    JSONObject location = new JSONObject();
                    location.put("longitude", locationRealArray[i][0]);
                    location.put("latitude", locationRealArray[i][1]);
                    if((double) res2[3] == 0.0)
                    {
                        location.put("err", locationRealArray[i][2]);
                    }
                    locationRealJsonArray.add(location);
                }
            }
            result.put("location_real", locationRealJsonArray);

            // 解析LocationError_avg数据
            double locationErrorAvg = 0.0;
            if(res2[2] != null)
            {
                locationErrorAvg = (double) res2[2];
            }
            result.put("LocationError_avg", locationErrorAvg);

            // 解析T数据
            double tData = 0.0;
            if(res2[3] != null)
            {
                tData = (double) res2[3];
            }
            result.put("T", tData);

            // 解析point1数据
            JSONArray point1JsonArray = new JSONArray();
            if(res2[4] != null)
            {
                double[][] point1Array = (double[][]) res2[4];
                for (int i = 0; i < point1Array.length; i++) {
                    log.debug("point1 [" + i + "] X =: " + point1Array[i][0] + "; Y =: " + point1Array[i][1] + "; Z =: " + point1Array[i][2]);
                    JSONObject point1JsonObj = new JSONObject();
                    point1JsonObj.put("longitude", point1Array[i][0]);
                    point1JsonObj.put("latitude", point1Array[i][1]);
                    point1JsonArray.add(point1JsonObj);
                }
            }
            result.put("point1", point1JsonArray);

            // 解析point2数据
            JSONArray point2JsonArray = new JSONArray();
            if(res2[5] != null)
            {
                double[][] point2Array = (double[][]) res2[5];
                for (int i = 0; i < point2Array.length; i++) {
                    log.debug("point2 [" + i + "] X =: " + point2Array[i][0] + "; Y =: " + point2Array[i][1] + "; Z =: " + point2Array[i][2]);
                    JSONObject point2JsonObj = new JSONObject();
                    point2JsonObj.put("longitude", point2Array[i][0]);
                    point2JsonObj.put("latitude", point2Array[i][1]);
                    point2JsonArray.add(point2JsonObj);
                }
            }
            result.put("point2", point2JsonArray);

            String newStatus = "计算完成";
            log.debug( newStatus);
            log.debug( result.toString());
            adsbHistoryDataService.updateStatusAndResultByID(id, newStatus, result.toString());
        } catch (Exception e) {
            log.error("startCalculLocatAndDetect", e);
            return AjaxResult.error("ADS-B干扰分析失败");
        }
        return AjaxResult.success("adsb数据保存成功。");
    }

    /**
     * 获取最新的lastCount条数据。
     * @return
     */
    @GetMapping("/queryAdsbLastRecord")
    public AjaxResult queryJszLastRecord(int lastCount){
        try {
            List<TAdsbHistoryData> historyDataList = adsbHistoryDataService.getLatestNRecords(lastCount);
            return AjaxResult.success(historyDataList);
        } catch (Exception  e) {
            log.error("startCalculLocatAndDetect", e);
            return AjaxResult.error("处理失败");
        }
    }
}
